//Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using Eas.WebCrawler.PlugIns;
using Eas.WebCrawler.Interfaces;

namespace Eas.WebCrawler.PlugIns.FileNamers {
    /// <summary>Creates a filename that includes the entire <see cref="Uri"/> of the request in the name.</summary>
    /// <remarks>This class creates a filename out of the <see cref="Uri"/> in the passed in <see cref="Request"/> by striping off the protocol (i.e. http://) and then replacing all invalid characters in the <see cref="Uri"/> (including the path seperator) with underscores.
    /// Duplicates are handled by appending _1, _2 ...  
    /// This class differs from the <see cref="FullUrlNamer"/> in that this class will include the host name directory structure in the resulting file name.</remarks>
    /// <example>The url http://www.erik.com/saltwell/default.html will return www_erik_com_saltwell_default.html if no other file of that name exists in the base directory.</example>
    public class FullUrlNamer : FileNamer {
        #region FileNamer Members

        /// <summary>Returns the name of a non-existant file in the passed-in <paramref name="baseDirectory"/>.</summary>
        /// <param name="request">The <see cref="Request"/> for which a file name should be created.</param>
        /// <param name="baseDirectory">The directory into which the file will be saved.</param>
        /// <returns>The <see cref="Uri"/> of the <paramref name="request"/> with all invalid characters and path seperators replaced by underscores.</returns>
        public string GetFileName(Request request, System.IO.DirectoryInfo baseDirectory) {
            string originalPath = request.Uri.Host + request.Uri.AbsolutePath;
            originalPath = NameHelper.EscapeFileName(originalPath);
            string extension = System.IO.Path.GetExtension(originalPath);
            StringBuilder bldr = new StringBuilder(originalPath.Length);
            originalPath = originalPath.Substring(0, originalPath.Length - extension.Length);
            foreach (char c in originalPath) {
                if (char.IsLetterOrDigit(c))
                    bldr.Append(c);
                else
                    bldr.Append('_');
            }
            originalPath = bldr.ToString();
            return NameHelper.AppendFileNumber(originalPath + extension, baseDirectory);
        }
        #endregion

        #region WebCrawlerComponent Members
        /// <summary>Initializes this class</summary>
        /// <param name="context">The <see cref="WebCrawlerContext"/> which will contain data about this instance of the web crawler.</param>
        public void Initialize(WebCrawlerContext context) { }
        #endregion
    }
}
